package com.wushijia.classload;

import java.io.File;
import java.io.IOException;
import java.io.InputStream;
import java.util.Properties;

/**
 * description:Class.getResource和Class.getResourceAsStream在使用时，路径选择上是一样的
 *
 * @author yang
 * @date 2018/5/17 11:04
 */
public class GetSourcesTest {

  public static void main(String[] args) throws IOException {

    GetSourcesTest t = new GetSourcesTest();
    System.out.println(GetSourcesTest.class.getResource(""));
    System.out.println(GetSourcesTest.class.getResource("/"));
    System.out.println(GetSourcesTest.class.getResource("1.properties"));
    System.out.println(GetSourcesTest.class.getResource("/1.properties"));

    System.out.println(GetSourcesTest.class.getClassLoader());
    System.out.println(t.getClass().getClassLoader());
    System.out.println(t.getClass().getClassLoader().getResource(""));
    System.out.println(t.getClass().getClassLoader().getResource("/"));//null

//    File file = new File("1.properties");
    //使用类的相对路径
    File file1 = new File(GetSourcesTest.class.getResource("1.properties").getFile());
    //和上面带/的通过类路径一样，都属于使用绝对路径--类路径来获取
    File file2 = new File(t.getClass().getClassLoader().getResource("1.properties").getFile());
    File file3 = new File(Thread.currentThread().getContextClassLoader().getResource("1.properties").getFile());
    //web项目下
    //File file = new File(getServletContext().getRealPath("/WEB-INF/classes/test.txt"));

    //相当于getSource包装了一层FileInputStream
    InputStream inputStream = Thread.currentThread().getContextClassLoader().getResourceAsStream("1.properties");

    Properties properties = new Properties();
    properties.load(inputStream);
    System.out.println(properties.getProperty("test"));
  }
}
